#-*- coding:utf-8 -*-
import os
import sys
import pymongo
import datetime

import json
# from pymongo.objectid import ObjectId
from bson.objectid import ObjectId

conn = pymongo.Connection('127.0.0.1' , 27017);
# 选择数据库
db   = conn['MyTest']
# 获取 表
user = db.user;
# print db.collection_names();
# print db.tables;
# print db.stats;

reload(sys)
sys.setdefaultencoding("utf-8")
#print sys.getdefaultencoding()

# 插入记录
# db.user.insert({"name":"李大伟" , "age" : 21 , "date" : datetime.datetime.now()});
# w = 2 表示 它被写入至少有一个 replica set 的 2 个 服务器才算成功
# insert_id = db.user.insert({"name":"李大伟11" , "age" : 21 , "date" : datetime.datetime.now()} , 2);

# 删除记录
# print db.user.remove({"_id":ObjectId("5640dcbe76314522a1542cb0")})
# print db.user.remove({"_id" , ObjectId(insert_id)})
# 更新记录
print db.user.update({"_id":ObjectId('5640eb0e763145241181c893')} , {"$set" : {"name":'茗予'}})

# 查询 一条数据

print db.user.find_one();
print db.user.find_one({"name":"李大伟"});

print u'记录总计:' , db.user.count() , db.user.find().count()
print u'查询单条记录：',db.user.find_one()

# for item in list(db.user.find()):
# 	print 'list : ' , item['name']

for item in db.user.find().sort([('age' , pymongo.ASCENDING) , ('date',pymongo.DESCENDING)]):
	# print item
	if item.has_key('date'):
		print 'Name:',item["name"] , '--age:--' , item['age'] , '--id--' , item['_id'] , '---' , item['date']
	else:
		print 'Name:',item["name"] , '--age:--' , item['age'] , '--id--' , item['_id']
	# if isinstance(item["name"] , unicode):
	# 	print (item["name"].encode('utf-8')).encode('gb2312') , '-1--'
	# else:
	# 	print item["name"].encode('gb2312') , "--2-\n"

#分析查询语句的性能
# db.user.create_index([("age", pymongo.ASCENDING), ("date", pymongo.DESCENDING)])#加索引
# print db.user.find().sort([("age",pymongo.ASCENDING),('date',pymongo.DESCENDING)]).explain()["cursor"]#未加索引用BasicCursor查询记录
# print db.user.find().sort([("age",pymongo.ASCENDING),('date',pymongo.DESCENDING)]).explain()["nscanned"]#查询语句执行时查询的记录数

